package method

import (
	"fmt"
	"net/http"
	"server/biz"
	"server/service"
)

func AfterLogin(r *http.Request, w http.ResponseWriter, state string) {
	if state == "account" {
		http.Redirect(w, r, "/account.html", http.StatusFound)
		return
	} else if state == "pc" {
		http.Redirect(w, r, "/pc.html", http.StatusFound)
		return
	}
	http.Redirect(w, r, "/v3.html", http.StatusFound)
}

func WxLogin(md *service.Meta, w http.ResponseWriter) {
	code := md.Get("code").String()
	state := md.Get("state").String()
	user_id := biz.GetCookieUserId(md.Request)
	if user_id != 0 {
		fmt.Println("已登陆")
		AfterLogin(md.Request, w, state)
		return
	}
	// local test
	//user := biz.CheckWxUser("o001", "cat1")
	//fmt.Println("checkuser:", user)
	//biz.SignIn(user, w)
	//return
	if code == "" {
		biz.WxOauth.Redirect(w, md.Request, "https://shop.gampal.com/v1/wxlogin", "snsapi_userinfo", state)
		return
	} else {
		result, err := biz.WxOauth.GetUserAccessToken(code)
		if err != nil {
			fmt.Fprintln(w, err)
			return
		}
		fmt.Println("accesstoken:", result.AccessToken)
		info, err := biz.WxOauth.GetUserInfo(result.AccessToken, result.OpenID, "zh_CN")
		if err != nil {
			fmt.Fprintln(w, err)
			return
		}
		fmt.Println("info:", info)
		user := biz.CheckWxUser(info.OpenID, info.Nickname, info.HeadImgURL)
		fmt.Println("checkuser:", user)
		biz.SignIn(user, w)
		AfterLogin(md.Request, w, state)
	}
	return
}
